<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>医疗排班系统登录</h2>
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        label-width="80px"
        @submit.prevent="handleLogin"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="loginForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="loading">
            登录
          </el-button>
          <el-button @click="goToRegister">没有账号？去注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { listUsertable } from '@/api/usertable'

const router = useRouter()
const loginForm = reactive({
  userName: '',
  password: ''
})

const loginRules = ref({
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const loading = ref(false)
const loginFormRef = ref(null)

const handleLogin = async () => {
  try {
    loading.value = true
    await loginFormRef.value.validate()

    const data  = await listUsertable({
      userName: loginForm.userName,
      password: loginForm.password
    })
    
    console.log('data',data)

    if (data && data.length > 0) {
      const user = data[0]
      localStorage.setItem('userInfo', JSON.stringify(user))
      
      // 根据角色跳转到不同页面
      switch(user.roleId) {
        case 2: // 排班员
          router.push('/scheduler')
          break
        default:
          ElMessage.error('用户名或密码错误')
      }
    } else {
      ElMessage.error('用户名或密码错误')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请重试')
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}
</style>